﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.Threading;
using System.IO.IsolatedStorage;
using System.IO;


namespace PhoneApp3
{
    public partial class StrokePanel : PhoneApplicationPage
    {
        private Point currentPoint;
        private Point oldPoint;
        private Boolean characterThumbnail;
        private String[] Chidefinitions;
        private String[] ChifileNames;
        private String[] Japdefinitions;
        private String[] JapfileNames;
        private String[] Engdefinitions;
        private String[] EngfileNames;
        private String[] Aradefinitions;
        private String[] ArafileNames;
        private String[] definitions;
        private String[] fileNames;

        int index;
        // Constructor
        public StrokePanel()
        {
            InitializeComponent();
            Chidefinitions = new string[] { "Tree", "Goat", "Man", "Cat" };
            ChifileNames = new string[] { "zi02812", "man", "boom", "doom" };
            Japdefinitions = new string[] { "Tree", "Goat", "Man", "Da" };
            JapfileNames = new string[] { "Ka", "Ko", "Du", "doom" };
            Aradefinitions = new string[] { "Tree", "Goat", "Man", "Cat" };
            ArafileNames = new string[] { "Beheh", "Feh", "Dad", "Zay" };
            Engdefinitions = new string[] { "A", "I", "G", "Z", "H" };
            EngfileNames = new string[] { "a", "i", "g", "z", "h" };
            setLanguage();
            //definitions = Chidefinitions;
            //fileNames = ChifileNames;
            String imageName = (String)fileNames[0];
            BitmapImage bip = new BitmapImage(new Uri("Characters/" + imageName + ".png", UriKind.Relative));
            image1.Source = bip;


            textBlock1.Text = (String)definitions[0];

            BackgroundImage.Source = new BitmapImage(new Uri("Characters/Big" + imageName + ".png", UriKind.Relative));
            index = 0;
            
            characterThumbnail = true;
            this.ContentPanelCanvas.MouseMove += new MouseEventHandler(ContentPanelCanvas_MouseMove);
            this.ContentPanelCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(ContentPanelCanvas_MouseLeftButtonDown);
            this.ClearButton.Click += new RoutedEventHandler(ClearButton_Click);
            this.NextButton.Click += new RoutedEventHandler(NextButton_Click);
            this.NewButton.Click += new RoutedEventHandler(NewButtonClick);
        }

        private void ContentPanelCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            currentPoint = e.GetPosition(ContentPanelCanvas);
            oldPoint = currentPoint;
        }

        private void setLanguage()
        {
            if (AppSettings.TryGetSetting<bool>("Japanese", true))
            {
                definitions = Japdefinitions;
                fileNames = JapfileNames;
            }
            if (AppSettings.TryGetSetting<bool>("Chinese", true))
            {
                definitions = Chidefinitions;
                fileNames = ChifileNames;
            }
            if (AppSettings.TryGetSetting<bool>("English", true))
            {
                definitions = Engdefinitions;
                fileNames = EngfileNames;
            }
            if (AppSettings.TryGetSetting<bool>("Arabic", true))
            {
                definitions = Aradefinitions;
                fileNames = ArafileNames;
            }
        }

        private void ContentPanelCanvas_MouseMove(object sender, MouseEventArgs e)
        {
            Point point = e.GetPosition(this.ContentPanelCanvas);

            Line line = new Line();
            line.Stroke = new SolidColorBrush(Colors.Black);
            line.X1 = point.X;

            line.Y1 = point.Y;

            line.X2 = oldPoint.X;

            line.Y2 = oldPoint.Y;

            line.StrokeStartLineCap = PenLineCap.Round;

            line.StrokeEndLineCap = PenLineCap.Round;

            line.StrokeThickness = 15;

            line.Opacity = 1;

            this.ContentPanelCanvas.Children.Add(line);

            oldPoint = point;

        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            NextButton.Visibility = Visibility.Visible;
            NewButton.Visibility = Visibility.Collapsed;
            if (characterThumbnail)
            {
                image1.Visibility = Visibility.Visible;
            }
            this.ContentPanelCanvas.Children.Clear();
            this.ContentPanelCanvas.Background = new SolidColorBrush(Colors.White);
            this.ContentPanelCanvas.Children.Add(image1);
        }



        private void image1_Tap(object sender, GestureEventArgs e)
        {
            /**
            characterThumbnail = !characterThumbnail;
            if (characterThumbnail)
            {
                image1.Visibility = Visibility.Visible;
            }
            else
            {
                image1.Visibility = Visibility.Collapsed;
            }
            */

        }

        private void NewButtonClick(object sender, RoutedEventArgs e)
        {
            textBlock2.Visibility = Visibility.Collapsed;
            //bool isSelected = true;

            
            if (index < definitions.Length)
            {
                NextButton.Visibility = Visibility.Visible;
                NewButton.Visibility = Visibility.Collapsed;
                image1.Visibility = Visibility.Visible;
                this.ContentPanelCanvas.Children.Clear();
                this.ContentPanelCanvas.Background = new SolidColorBrush(Colors.White);
                this.ContentPanelCanvas.Children.Add(image1);

                String imageName = (String)fileNames[index];
                BitmapImage bip = new BitmapImage(new Uri("Characters/" + imageName + ".png", UriKind.Relative));
                image1.Source = bip;


                textBlock1.Text = (String)definitions[index];

                BackgroundImage.Source = new BitmapImage(new Uri("Characters/Big" + imageName + ".png", UriKind.Relative));
                //image1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Characters/Bigman.png");
                index = index + 1;
            }
            else
            {
                NavigationService.Navigate(new Uri("/EndScreen.xaml", UriKind.Relative));

            }
        }
        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            image1.Visibility = Visibility.Collapsed;
            this.ContentPanelCanvas.Background = new SolidColorBrush(Colors.White);
            NextButton.Visibility = Visibility.Collapsed;
            NewButton.Visibility = Visibility.Visible;
            compareImageForPercent.Visibility = Visibility.Collapsed;
            try
            {

                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isf.FileExists("Images1.jpg"))
                    {
                        isf.DeleteFile("Images1.jpg");
                    }
                    IsolatedStorageFileStream fstream = isf.CreateFile("Images1.jpg");

                    WriteableBitmap wbmp = new WriteableBitmap(ContentPanelCanvas, null);
                    Extensions.SaveJpeg(wbmp, fstream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
                    fstream.Close();
                }

                BitmapImage bi = new BitmapImage();

                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("Images1.jpg", FileMode.Open, FileAccess.Read))
                    {
                        bi.SetSource(fileStream);
                    }
                }
                //When reimplementing this: You might want to add a check to see if the index is too high. Cause it isn't done here.
                //String imageName = (String)fileNames[index];
                compareImageForPercent.Source = new BitmapImage(new Uri("Characters/test.png", UriKind.Relative));
                BitmapSource biCource = (BitmapSource)compareImageForPercent.Source;
                WriteableBitmap writeableM = new WriteableBitmap(biCource);

                compareImageForPercent.Source = null;

                double percentage = ImageCompareArray(bi, writeableM) * 100.0;

                textBlock2.Visibility = Visibility.Visible;
                textBlock2.Text = percentage.ToString();
            }
            catch (NullReferenceException error)
            {
                Console.Out.Write(error.StackTrace);
            }
            this.ContentPanelCanvas.Background = new SolidColorBrush(Colors.Transparent);
        }

        private double ImageCompareArray(BitmapImage firstImage, WriteableBitmap secondImage)
        {
            double same = 0;

            string firstPixel;
            string secondPixel;

            WriteableBitmap wbFirstImage = new WriteableBitmap(firstImage);
            int[] firstImagePixels = wbFirstImage.Pixels;
            WriteableBitmap wbSecondImage = secondImage;


            int[] secondImagePixels = wbSecondImage.Pixels;
            double pixelCount = 0;
            for (int i = 0; i < firstImagePixels.Length; i++)
            {
                if (firstImagePixels[i] != -1)
                {
                    pixelCount++;
                    int check = firstImagePixels[i];
                    //firstPixel = firstImagePixels[i].ToString();
                    //secondPixel = secondImagePixels[i].ToString();
                    if (secondImagePixels[i] != -1)
                        same++;
                }
            }

            return (same / pixelCount);// (firstImage.PixelHeight * firstImage.PixelWidth);
        }

    }
}
